<?php

namespace App\Console\Commands\OpenShop;


use App\Enums\Check\CheckEnum;
use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Rms\RmsCurl;
use App\Library\Rms\RmsSysApi;
use App\Models\Check\CheckStreamModel;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Fee\FeeAnnualOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignCostMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftOutfitMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Service\Check\CheckStreamParam;
use App\Service\OpenShop\Feishu\KfosService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class AccountCheck extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:account-check {startTime} {endTime} {chatId}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开店 - 财务对账';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    private int $startTime;
    private int $endTime;
    private string $chatId;

    public function handle()
    {
        ini_set('memory_limit', '1024M');

        $this->startTime = $this->argument('startTime');
        $this->endTime   = $this->argument('endTime');
        $this->chatId    = $this->argument('chatId');

        if (!$this->startTime || !$this->endTime) {
            dd('开始结束时间不能为空');
        }

        $res = $this->league();
        $res = array_merge($this->other(), $res);
        $res = array_merge($this->fee(), $res);
        $res = array_merge($this->against(), $res);

        // 过滤测试门店
        foreach ($res as $k => $v) {
            if ($v[3] >= OpenShopSignOrderModel::SHOP_CODE_TEST) {
                unset($res[$k]);
            }
        }

        $res = array_values($res);

        $this->writeCsv(date('Y-m-d' . $this->startTime) . '开始的招商、设计、软装、设备、管理、违约费', $res);
    }

    private function writeCsv(string $name, array $res)
    {
        // UTF8的BOM头
        $url = storage_path("app/{$name}.csv");
        $fd  = fopen($url, 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        fputcsv($fd, [
            '最后支付时间',
            '下单时间',
            '订单编码',
            '门店编号',
            '加盟商名称',
            '物料编码',
            '物料名称',
            '税率',
            '数量',
            '金额',
            '是否支付成功',
            '收款账号',
            '收款方式',
            '出库单号',
            '发货的日期',
            '供应商',
            '发货的数量',
            '成本金额',
            '物料类型',
            '门店选址范围',
        ]);

        collect($res)->each(function ($item) use (&$fd) {

            $shopCode = $item[3];
            $orderNo = OpenShopSignOrderModel::query()->where('shopCode', $shopCode)->value('orderNo');
            if ($orderNo) {
                if (count($item) < 19) {
                    $item = array_pad($item, 19, '');
                }

                $item[] = (string)OpenShopAddressModel::query()->where('orderNo', $orderNo)->value('addressPrefix');
            }

            fputcsv($fd, $item);
        });
        // 根据bizId聚合
        $list = [];
        foreach ($res as $item) {
            if (!isset($list[$item[2]])) {
                $list[$item[2]] = [
                    'time'   => $item[0],
                    'amount' => 0
                ];
            }
            $list[$item[2]]['amount'] += $item[9];
        }
        fputcsv($fd, []);
        fputcsv($fd, []);
        fputcsv($fd, [
            '订单编号',
            '总金额',
            '最后支付时间',
            '第一次金额',
            '第一次流水',
            '第一次支付渠道流水',
            '第一次收款主体',
            '第二次金额',
            '第二次流水',
            '第二次支付渠道流水',
            '第二次收款主体',
            '第三次金额',
            '第三次流水',
            '第三次支付渠道流水',
            '第三次收款主体',
        ]);
        foreach ($list as $bizId => $item) {
            $item = [
                $bizId,
                $item['amount'],
                $item['time'],
            ];
            OpenShopSignOrderPayHistoryModel::query()
                                            ->where('bizId', $bizId)
                                            ->where('payStatus', 1)
                                            ->whereIn('payChannel', [1, 2])
                                            ->get()
                                            ->map(function ($model) use (&$item) {

                                                $thirdPayNo = RmsCurl::getIns()->setDomain('http://api-inner.51kuafu.com')->do('api/internal/pay/payDetails', ['payNos' => [$model->payNo], 'field' => ['payNo', 'thirdPayNo']], 'GET')['data']['lists'][0]['thirdPayNo'] ?? '';

                                                $item[] = $model->payPrice / 100;
                                                $item[] = "\t" . $model->payNo;
                                                $item[] = "\t" . $thirdPayNo;
                                                $item[] = CheckEnum::getBankCompany($model->sysType,
                                                        $model->createdAt->timestamp)[2] ?? '';
                                            });
            fputcsv($fd, $item);
        }

        if (is_resource($fd)) {
            fclose($fd);
        }

        $objectName = "tmp/".date('Ymd')."/".Str::random()."/material_detail.csv";
        $streamUrl = FileUtil::uploadFile($url, 'csv', $objectName)['url'];
//        dump($streamUrl);

        $param = (new \App\Service\Check\CheckStreamParam())
            ->setSysTypes([])
            ->setStartTime($this->startTime)
            ->setEndTime($this->endTime)
            ->setOrderId('')
            ->setPayNo('')
            ->setPageSize(99999)
            ->setPageNum(1)
            ->setCheckStatus(0)
            ->setPayChannel(0)
            ->setPayAction(0)
            ->setExport(CheckStreamParam::EXPORT_COMMAND);

        $detailUrl = (new \App\Service\Check\CheckStreamService($param))->streamLists()['url'] ?? '';

        $objectName = "tmp/".date('Ymd')."/".Str::random()."/pay_stream.csv";
        $detailUrl = FileUtil::uploadFile($detailUrl, 'csv', $objectName)['url'];
//        dump($detailUrl);

        $message = "物料明细表：[ {$streamUrl} ]" . PHP_EOL . PHP_EOL . "支付流水表：[ {$detailUrl} ]";
        Log::info("AccountCheck Message: {$message}");

        if ($this->chatId) {
            $send = (new RmsSysApi())->sendRobotMessage($message, $this->chatId);
            dump($send);
        }
    }

    private function against()
    {
        $res    = [];
        $bizIds = OpenShopSignOrderPayHistoryModel::query()
                                                  ->whereIn('sysType', [
                                                      CheckEnum::SYS_TYPE_AGAINST
                                                  ])
                                                  ->where('createdAt', '>=', $this->startTime)
                                                  ->where('payStatus',
                                                      OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                  ->groupBy('bizId')
                                                  ->pluck('bizId');


        // 违约函
        CruiseCheckAgainstModel::query()
                           ->with([
                               'signOrderRel',
                               'payHistoryRel' => function ($query) {
                                   $query->where('payStatus', OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK);
                               }
                           ])
                           ->whereIn('serialNum', $bizIds)
                           ->where('status', CruiseCheckAgainstModel::STATUS_OK)
                           ->get()
                           ->each(function ($item) use (&$res) {

                               if (!$item->payHistoryRel->count()) {
                                   return;
                               }

                               $payChannels = $item->payHistoryRel
                                   ->pluck('payChannel')->unique()
                                   ->values()
                                   ->map(function ($payChannel) {
                                       return CheckEnum::PAY_CHANNEL_TEXT[$payChannel] ?? '';
                                   })->implode('，');

                               $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->payHistoryRel->last()->orderNo ?? ''))->name;

                               $priceTypes = [
                                   'price' => ['加盟商违约金', 'D0021', '6%'],
                               ];

                               foreach ($priceTypes as $k => $v) {

                                   if ($item->$k == 0) {
                                       continue;
                                   }

                                   $res[] = [
                                       $item->payHistoryRel->last()->createdAt->toDateTimeString('minute'),
                                       $item->createdAt->toDateTimeString('minute'),
                                       $item->serialNum,
                                       $item->signOrderRel->last()->shopCode,
                                       $merchantName,
                                       $v[1],
                                       $v[0],
                                       $v[2],
                                       1,
                                       $item->$k / 100,
                                       '是',
                                       '厦门心有炸念餐饮管理有限公司',
                                       $payChannels,
                                   ];
                               }
                           });

        return $res;
    }


    private function fee()
    {
        $res    = [];
        $bizIds = OpenShopSignOrderPayHistoryModel::query()
                                                  ->whereIn('sysType', [
                                                      CheckEnum::SYS_TYPE_ANNUAL_FEE
                                                  ])
                                                  ->where('createdAt', '>=', $this->startTime)
                                                  ->where('payStatus',
                                                      OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                  ->groupBy('bizId')
                                                  ->pluck('bizId');


        // 管理费
        FeeAnnualOrderModel::query()
                           ->with([
                               'signOrderRel',
                               'payHistoryRel' => function ($query) {
                                   $query->where('sysType', CheckEnum::SYS_TYPE_ANNUAL_FEE)
                                         ->where('payStatus', OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK);
                               }
                           ])
                           ->whereIn('feeOrderNo', $bizIds)
                           ->where('payStatus', FeeAnnualOrderModel::PAY_STATUS_OK)
                           ->get()
                           ->each(function ($item) use (&$res) {
                               if (!$item->payHistoryRel->count()) {
                                   return;
                               }

                               $payChannels = $item->payHistoryRel
                                   ->pluck('payChannel')->unique()
                                   ->values()
                                   ->map(function ($payChannel) {
                                       return CheckEnum::PAY_CHANNEL_TEXT[$payChannel] ?? '';
                                   })->implode('，');

                               $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->payHistoryRel->last()->orderNo ?? ''))->name;

                               $priceTypes = [
                                   'manageFee' => ['年管理费', 'D0015', '6%'],
                                   'systemFee' => ['数字系统服务费', 'D0020', '6%'],
                               ];

                               foreach ($priceTypes as $k => $v) {

                                   if ($item->$k == 0) {
                                       continue;
                                   }

                                   $res[] = [
                                       $item->payHistoryRel->last()->createdAt->toDateTimeString('minute'),
                                       $item->createdAt->toDateTimeString('minute'),
                                       $item->feeOrderNo,
                                       (string)optional($item->signOrderRel)->shopCode,
                                       $merchantName,
                                       $v[1],
                                       $v[0],
                                       $v[2],
                                       1,
                                       $item->$k / 100,
                                       '是',
                                       '厦门心有炸念餐饮管理有限公司',
                                       $payChannels,
                                   ];
                               }
                           });

        return $res;
    }

    private function other()
    {
        $res      = [];
        $orderNos = OpenShopSignOrderPayHistoryModel::query()
                                                    ->whereIn('sysType', [
                                                        CheckEnum::SYS_TYPE_OPEN_SHOP_DESIGN,
//                                                        CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT,
                                                        CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE
                                                    ])
                                                    ->where('createdAt', '>=', $this->startTime)
                                                    ->where('payStatus',
                                                        OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                    ->distinct('orderNo')
                                                    ->pluck('orderNo');

        // 设计费
        OpenShopSpaceDesignCostMappingModel::query()
                                           ->with([
                                               'signOrderRel',
                                               'payHistoryRel' => function ($query) {
                                                   $query->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_DESIGN);
                                               }
                                           ])
                                           ->where('payStatus', '>=',
                                               OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2)
                                           ->whereIn('orderNo', $orderNos)
                                           ->where('orderStatus', ">=",
                                               OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_1)
                                           ->get()
                                           ->each(function ($item) use (&$res) {
                                               if ($item->signOrderRel->status == SignOrderEnum::ORDER_STATUS_NO) {
                                                   return;
                                               }

                                               if (!$item->payHistoryRel->where('bizId', $item->preparationNo)
                                                                        ->count()) {
                                                   return;
                                               }

                                               $priceTypes = [
                                                   'designFee'   => ['设计费', 'D0012', '6%'],
                                                   'merchantFee' => ['商户通', 'D0018', '6%'],
                                               ];

                                               $payChannels = $item->payHistoryRel
                                                   ->pluck('payChannel')->unique()
                                                   ->values()
                                                   ->map(function ($payChannel) {
                                                       return CheckEnum::PAY_CHANNEL_TEXT[$payChannel] ?? '';
                                                   })->implode('，');

                                               if ($item->payHistoryRel->last()->createdAt->timestamp >= 1655428500) {
                                                   $company = '厦门心有炸念餐饮管理有限公司';
                                               } else {
                                                   $company = '厦门万皮思供应链管理有限公司';
                                               }

                                               $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->orderNo))->name;

                                               foreach ($priceTypes as $priceType => $v) {
                                                   if ($priceType == 'designFee') {
                                                       $price = $item->designFee + $item->overDesignFee;
                                                   } else {
                                                       $price = $item->merchantFee;
                                                   }

                                                   $res[] = [
                                                       $item->payHistoryRel->where('bizId', $item->preparationNo)
                                                                           ->last()->createdAt->toDateTimeString('minute'),
                                                       $item->createdAt->toDateTimeString('minute'),
                                                       $item->preparationNo,
                                                       $item->signOrderRel->shopCode,
                                                       $merchantName,
                                                       $v[1],
                                                       $v[0],
                                                       $v[2],
                                                       1,
                                                       $price / 100,
                                                       '是',
                                                       $company,
                                                       $payChannels,
                                                   ];
                                               }
                                           });


        // 软装费
        OpenShopSpaceDesignSoftOutfitMappingModel::query()
                                                 ->with([
                                                     'signOrderRel',
                                                     'payHistoryRel' => function ($query) {
                                                         $query->where('sysType',
                                                             CheckEnum::SYS_TYPE_OPEN_SHOP_DECORATE);
                                                     }
                                                 ])
                                                 ->where('payStatus', '>=',
                                                     OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_2)
                                                 ->whereIn('orderNo', $orderNos)
                                                 ->where('orderStatus', ">=",
                                                     OpenShopSpaceDesignSoftOutfitMappingModel::ORDER_STATUS_1)
                                                 ->get()
                                                 ->each(function ($item) use (&$res) {
                                                     if ($item->signOrderRel->status == SignOrderEnum::ORDER_STATUS_NO) {
                                                         return;
                                                     }

                                                     if (!$item->payHistoryRel->where('bizId', $item->preparationNo)
                                                                              ->count()) {
                                                         return;
                                                     }

                                                     $priceTypes = [
                                                         'fee' => ['软装费', 'D0012', '6%'],
                                                     ];

                                                     $payChannels = $item->payHistoryRel
                                                         ->pluck('payChannel')->unique()
                                                         ->values()
                                                         ->map(function ($payChannel) {
                                                             return CheckEnum::PAY_CHANNEL_TEXT[$payChannel] ?? '';
                                                         })->implode('，');

                                                     $company = '厦门万皮思供应链管理有限公司';

                                                     $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->orderNo))->name;

                                                     foreach ($priceTypes as $priceType => $v) {
                                                         $res[] = [
                                                             $item->payHistoryRel->where('bizId', $item->preparationNo)
                                                                                 ->last()->createdAt->toDateTimeString('minute'),
                                                             $item->createdAt->toDateTimeString('minute'),
                                                             $item->preparationNo,
                                                             $item->signOrderRel->shopCode,
                                                             $merchantName,
                                                             $v[1],
                                                             $v[0],
                                                             $v[2],
                                                             1,
                                                             $item->$priceType / 100,
                                                             '是',
                                                             $company,
                                                             $payChannels,
                                                         ];
                                                     }
                                                 });
        // 设备费
        OpenShopSignOrderPayHistoryModel::query()
                                        ->with('signOrderRel')
                                        ->whereIn('sysType', [
                                            CheckEnum::SYS_TYPE_OPEN_SHOP_EQUIPMENT,
                                        ])
                                        ->where('createdAt', '>=', $this->startTime)
                                        ->where('payStatus',
                                            OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                        ->groupBy('bizId')
                                        ->get()
                                        ->each(function ($item) use (&$res) {
                                            $lists = collect(KfosService::myEquipments($item->orderNo))->where('code',
                                                $item->bizId);

                                            $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->orderNo))->name;

                                            foreach ($lists as $v) {
                                                $createdAt = OpenShopSiteMissionModel::query()
                                                                                     ->where('orderNo', $item->orderNo)
                                                                                     ->where('stepStatus',
                                                                                         MissionTemplateEnum::STEP_STATUS_16)
                                                                                     ->where('status',
                                                                                         SiteMissionEnum::STATUS_2)
                                                                                     ->value('createdAt');

                                                $res[] = [
                                                    $item->createdAt->toDateTimeString('minute'),
                                                    $createdAt ? $createdAt->toDateTimeString('minute') : '',
                                                    $v['code'],
                                                    $item->signOrderRel->shopCode,
                                                    $merchantName,
                                                    $v['goods_code'],
                                                    $v['name'],
                                                    "13%",
                                                    $v['num'],
                                                    bcmul($v['saleUnitPrice'], $v['num'], 2),
                                                    '是',
                                                    '厦门万皮思供应链管理有限公司',
                                                    CheckEnum::PAY_CHANNEL_TEXT[$item->payChannel] ?? '',
                                                    '-',
                                                    '-',
                                                    '-',
                                                    '-',
                                                    $v['num'] * $v['costUnitPrice'],
                                                    '-',
                                                ];

                                                $this->info("equipment orderNo:{$item->orderNo}");
                                            }
                                        });


        return $res;
    }

    private function league()
    {
        $res      = [];
        $orderNos = OpenShopSignOrderPayHistoryModel::query()
                                                    ->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                                    ->where('payTime', '>=', $this->startTime)
                                                    ->where('payStatus',
                                                        OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                                    ->distinct('orderNo')
                                                    ->pluck('orderNo');

        OpenShopSignOrderModel::query()
                              ->with('payHistoryRel', 'contractRel')
                              ->with([
                                  'contractRel',
                                  'payHistoryRel' => function ($query) {
                                      $query->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                            ->where('payStatus', OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK);
                                  }
                              ])
                              ->whereIn('payStatus', [SignOrderEnum::PAY_STATUS_OK, SignOrderEnum::PAY_STATUS_PART])
                              ->whereIn('orderNo', $orderNos)
                              ->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                              ->get()
                              ->each(function (OpenShopSignOrderModel $item) use (&$res) {

                                  if (!$item->payHistoryRel
                                          ->first() || !$item->contractRel) {
                                      return;
                                  }

                                  $priceTypes = [
                                      'initialFee'            => ['品牌使用费', 'D0013', '6%',],
                                      'technologyTransferFee' => ['技术服务费', 'D0014', '6%'],
                                      'guidanceFee'           => ['咨询指导服务费', 'D0019', '6%'],
                                      'managementCost'        => ['年管理费', 'D0015', '6%'],
                                      'decorationDeposit'     => ['装修保证金', 'D0016', '-'],
                                      'deposit'               => ['加盟商押金', 'D0017', '-'],
                                  ];

                                  $payChannels = $item->payHistoryRel
                                      ->pluck('payChannel')->unique()->values()
                                      ->map(function ($payChannel) {
                                          return CheckEnum::PAY_CHANNEL_TEXT[$payChannel] ?? '';
                                      })->implode('，');

                                  $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($item->orderNo))->name;

                                  // 定金模式特殊处理
                                  if ($item->contractRel->mode == OpenShopContractTemplateModel::MODE_3) {

                                      if ($item->signTime > 0) {

                                          // 定金金额
                                          $dj = (int)$item->payHistoryRel->where('payTime', '<=', $item->signTime)
                                                                         ->sum('payPrice');

                                          // 尾款金额
                                          $wk = (int)$item->payHistoryRel->where('payTime', '>', $item->signTime)
                                                                         ->sum('payPrice');

                                      } else {
                                          $dj = (int)$item->payHistoryRel->sum('payPrice');
                                          $wk = 0;
                                      }

                                      $priceTypes = [];
                                      $priceNum = 0;

                                      if ($dj > 0) {
                                          $priceTypes = array_merge($priceTypes, [
                                              'initialFee'            => ['品牌使用费', 'D0013', '6%', $item->contractRel->initialFee],
                                              'technologyTransferFee' => ['技术服务费', 'D0014', '6%', $item->contractRel->technologyTransferFee],
                                              'guidanceFee'           => ['咨询指导服务费', 'D0019', '6%', $item->contractRel->guidanceFee],
                                          ]);

                                          $priceNum += $dj;
                                      }

                                      if ($wk > 0) {

                                          $priceTypes = array_merge($priceTypes, [
                                              'managementCost'        => ['年管理费', 'D0015', '6%',  $item->contractRel->managementCost / $item->contractRel->shopCount],
                                              'decorationDeposit'     => ['装修保证金', 'D0016', '-', $item->contractRel->decorationDeposit / $item->contractRel->shopCount],
                                              'deposit'               => ['加盟商押金', 'D0017', '-', $item->contractRel->deposit / $item->contractRel->shopCount],
                                          ]);

                                          $priceNum += $wk;
                                      }

                                      // 按顺序拆分金额
                                      foreach ($priceTypes as &$vv) {
                                          $shouldPrice = $vv[3];

                                          if ($priceNum <= 0) {
                                              $vv[3] = 0;
                                              continue;
                                          }

                                          if ($priceNum < $shouldPrice) {
                                              $vv[3] = $shouldPrice - $priceNum;
                                          }

                                          $priceNum -= $shouldPrice;
                                      }
                                  }

                                  foreach ($priceTypes as $priceType => $v) {
                                      $res[] = [
                                          $item->payHistoryRel->last()->createdAt->toDateTimeString('minute'),
                                          $item->createdAt->toDateTimeString('minute'),
                                          $item->orderNo,
                                          $item->shopCode,
                                          $merchantName,
                                          $v[1],
                                          $v[0],
                                          $v[2],
                                          1,
                                          isset($v[3]) ? ($v[3] / 100) : round($item->contractRel->{$priceType} / 100 / $item->contractRel->shopCount, 2),
                                          '是',
                                          '厦门心有炸念餐饮管理有限公司',
                                          $payChannels,
                                      ];
                                  }
                              });

        return $res;
    }

    private function checkCheckStream()
    {
        OpenShopSignOrderPayHistoryModel::query()
                                        ->where('sysType', CheckEnum::SYS_TYPE_OPEN_SHOP_LEAGUE)
                                        ->where('payTime', '>=', strtotime(20231201))
                                        ->where('payStatus',
                                            OpenShopSignOrderPayHistoryModel::PAY_STATUS_OK)
                                        ->get()
                                        ->each(function ($item) {
                                            $q = CheckStreamModel::query()->where('orderId', $item->bizId)
                                                                 ->select(DB::raw(1))->first();
                                            if (!$q) {
                                                $this->info($item->id . ' - ' . $item->orderNo . ' 未同步check_stream ' . $item->payPrice);

                                                // check_streams
//                                                            $lastSysTypeCheckStream = CheckStreamModel::query()
//                                                                                                      ->where('sysType', $item->sysType)
//                                                                                                      ->orderByDesc('id')
//                                                                                                      ->first();
//                                                            CheckStreamModel::query()->insert([
//                                                                'tradeTime'       => $item->payTime,
//                                                                'date'            => date('Ymd', $item->payTime),
//                                                                'orderId'         => $item->orderNo,
//                                                                'subject'         => $item->subject,
//                                                                'sysType'         => $item->sysType,
//                                                                'orderPrice'      => $item->payPrice,
//                                                                'tradePrice'      => $item->payPrice,
//                                                                'incomePrice'     => $item->payPrice,
//                                                                'feePrice'        => 0,
//                                                                'feeRate'         => 0,
//                                                                'thirdPayNo'      => '',
//                                                                'company'         => $lastSysTypeCheckStream->company,
//                                                                'companyAccount'  => $lastSysTypeCheckStream->companyAccount,
//                                                                'payNo'           => '',
//                                                                'payChannel'      => $item->payChannel,
//                                                                'payChannelChild' => 0,
//                                                                'payAction'       => 0,
//                                                                'checkStatus'     => 0,
//                                                                'createdAt'       => $item->payTime,
//                                                                'updatedAt'       => $item->payTime,
//                                                                ]);


                                            }
                                        });

    }
}
